<template>
    <el-date-picker
            v-model.trim="value"
            :align="align"
            :type="uiType"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :format="format"
            :picker-options="pickerOptions"
            :popper-class="format =='yyyy-MM-dd HH:mm:ss'?'':'onlyhour'"
            :value-format="format"
            :clearable="clearable"
    ></el-date-picker>
</template>
<script>

export default {
  data() {
    return {
      value: this.defVal,
      maxDate: null,
      minDate: null,
      pickerOptions: {
        // 当我们选择日期时的回调方法。返回两个日期的最大值和最小值，第一次返回一个值，第二次返回两个值
        onPick: ({ maxDate, minDate }) => {
          // 当我们选择两个值的时候，就认为用户已经选择完毕
          if (maxDate != null && minDate != null) {
            this.maxDate = maxDate;
            this.minDate = minDate;
          }
        },
        // disabledDate: time => {
        //   let maxDate = this.maxDate;
        //   let minDate = this.minDate;
        //   if (maxDate != null && minDate != null) {
        //     let days = maxDate.getTime() - minDate.getTime(); // 计算完之后必须清除，否则选择器一直处于禁止选择的状态
        //     this.maxDate = null;
        //     this.minDate = null;
        //     if (parseInt(days / (1000 * 60 * 60 * 24)) > this.abledDate) {
        //       this.$message.warning('时间范围为' + this.abledDate + '天内！');
        //       return true
        //     } else {
        //       return false
        //     }
        //
        //   } else {
        //     // 设置当前时间后的时间不可选
        //     return time.getTime() > Date.now();
        //   }
        // }
      }
    };
  },
  props: {
    uiType: {
      type: String,
      default: 'datetimerange'
    },
    defVal: {
      type: Array
    },
    def: {
      default: true
    },
    clearable: {
      default: true
    },
    align: {
      type: String,
      default: 'left'
    },
    format: {
      type: String,
      default: 'yyyy-MM-dd HH:mm:ss'
    }
  },
  watch: {
    value: {
      handler(newval, oldval) {
        if (!newval) newval = ['', ''];
        this.$emit('update-date', newval);
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    cleanDate() {
      this.value = []
    }
  },
  created() {
    if (this.def) {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      this.$set(this.value, 0, start.format('yyyy-MM-dd'));
      this.$set(this.value, 1, end.format('yyyy-MM-dd'));
    }
  }
};
</script>
